Often we will want to insert/inject variables into string eg. my_name = "Russ"
print("Hi " + my_name)
String Interpolation refers to formatting strings in various ways to permit injection.
Explorations of the .format() method/function and the f-strings (formatted string literals) newer in Python3.6.x plus
In [27]:
print('This is a String {}'.format('INSERTED'))
In [28]:
print('This is an example of MultiIndex insertions {} {} {}'.format('INSERTION1', 'INSERTION2', 'INSERTION3'))
In [29]:
a = 'I1'
b = 'I2'
c = 'I3'
In [30]:
print('This is me jumping the gun and testing a theory {} {} {}'.format(a, b, c))
In [31]:
print('Now testing MultiIndexed Insertions without jumping the gun:' + 'The {2} {1} {0}'.format('fox', 'brown', 'quick'))
Can also repeat an index eg. {0} {0} {0} - and use K2VP as below - cannot use numerical values (expressions and maloc rules).
In [32]:
print('The {q} {g} {f}'.format(f='fox', q='quick', g='golden'))
Repeat can also be used with keys: {f} {f} {f}
Float formatting follows "{value:width.precision f}"
In [33]:
result = 12987/8921
In [34]:
result
Out[34]:
In [35]:
print('The result was {}'.format(result))
In [36]:
print('The result was {r:1.6f}'.format(r=result))
Formatted String literals AKA 'FString'.
In [37]:
name = 'Rusha'
In [39]:
print(f'Hi, he said his name was {name} because he drinks too much caffeine and rushes around.')
In [44]:
age = 3000
real_name = 'Russell'
hobbits = 'AI, Art and Coding among others.'
In [45]:
print(f'HI, he said his name was {name} because he drinks a lot of caffeine and rushes about. I later found out after getting to know him, his real name is {real_name} and he is {age} years old and has a keen interest in {hobbits}')
In [53]:
pi = u"\U0001D70B"
In [54]:
print(f'He also said he likes the idea of {pi}.')
In [ ]: